jQuery(document).ready(function ($) {

    //Setup add spinner dialog
    var $addDialog = $('#wv_add_spinner').dialog({
        autoOpen: false,
        modal: false,
        title: 'Add Spinner',
        width: 600,
        buttons: {
            'Cancel': function () {
                $(this).dialog('close');
            },
            'Insert': function () {
                tinyMCE.activeEditor.execCommand('mceInsertContent', false, $('#spinner-result').text());
                $(this).dialog('close');
            }
        }
    })

    //Setup preview spinner dialog
    var $previewDialog = $('#wv_preview_spinner').dialog({
        autoOpen: false,
        modal: false,
        title: 'Preview Result',
        width: 600,
        buttons: {
            'Close': function () {
                $(this).dialog('close');
            },
            'Refresh': function () {
                $('#wv_preview_spinner').text('Loading...');
                $.post(wvSettings.url + '/admin/preview-spinner.php',
                        {query: tinyMCE.activeEditor.getContent(), nonce: wvSettings.nonce},
                        function (data) {
                            $('#wv_preview_spinner').html(data);
                        });
            }
        }
    })

    //Add more input box
    $('#add-more-spinner').click(function (e) {
        $('<input type="text">').appendTo('#wv_add_spinner fieldset:first');
    })

    //Generate spinner's code
    $('#wv_add_spinner input').live('keyup', function () {
        var $text = wvSettings.leftchar;
        $('#wv_add_spinner input').each(function () {
            if (!$(this).val()) return;
            $text += $(this).val()
                    .replace(RegExp(escape(wvSettings.leftchar), 'g'), '\\' + wvSettings.leftchar)
                    .replace(RegExp(escape(wvSettings.rightchar), 'g'), '\\' + wvSettings.rightchar)
                    .replace(RegExp(escape(wvSettings.splitchar), 'g'), '\\' + wvSettings.splitchar);
            $text += wvSettings.splitchar;
        });
        $text = $text.slice(0, -wvSettings.splitchar.length); //Remove last splitchar
        $text += wvSettings.rightchar;
        $('#spinner-result').text($text);
    });
    function escape(str) {
        return str.replace(/(?=[\\^$*+?.()|{}[\]])/g, "\\");
    }


    //Open add spinner's dialog
    function WVAddSpinner (e) {
        $('#spinner-result').text('');
        $('#wv_add_spinner input').val('');
        $('#wv_add_spinner input:first').val(tinyMCE.activeEditor.selection.getContent());
        $addDialog.dialog('open');
    }

    //Open preview spinner's dialog
    function WVPreviewSpinner (e) {
        $('#wv_preview_spinner').text('Loading...');
        $.post(wvSettings.url + '/admin/preview-spinner.php',
            {query: tinyMCE.activeEditor.getContent(), nonce: wvSettings.nonce},
            function (data) {
                $('#wv_preview_spinner').html(data);
                $previewDialog.dialog('open');
        });
    }

    //Add and trigger buttons to tinyMCE
    (function () {
        tinymce.create('tinymce.plugins.wvmce', {
            init: function (ed, url) {
                //Add spinner button
                ed.addButton('wv_add_spinner', {
                    title: 'Add spinner',
                    image: url + '/../images/add_button.png',
                    onclick : function(e) {
                        WVAddSpinner(e);
                    }
                });

                //Preview spinners button
                ed.addButton('wv_preview_spinner', {
                    title: 'Preview spinners',
                    image: url + '/../images/preview_button.png',
                    onclick : function(e) {
                        WVPreviewSpinner(e);
                    }
                });
            },
            getInfo: function () {
                return {
                    longname: 'WordPress Vampire Word Spinner',
                    author: 'LongDH',
                    authorurl: 'http://www.wpvampire.com',
                    version: '1.0'
                };
            }
        });

        tinymce.PluginManager.add('wv_spinner', tinymce.plugins.wvmce);
    })();
})